package com.smilive.start.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: netty
 * @Date: 2022-01-05 10:54
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class NettySimpleServer {

    public static void main(String[] args) {
        //1.启动器
        new ServerBootstrap()
                //2.工作线程组
                .group(new NioEventLoopGroup())
                //3.选择服务器的 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                //4.ChannelInitializer 处理器（仅执行一次）
                //它的作用是待客户端SocketChannel建立连接后，执行initChannel以便添加更多的处理器
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //5.添加StringDecoder 字符串解码器
                        nioSocketChannel.pipeline().addLast(new StringDecoder());
                        //6.添加自定义入站处理器
                        nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println(s);
                            }
                        });
                    }
                })
                //7.ServerSocketChannel绑定8000端口
                .bind(8000);
    }
}
